#include "rtc_board.h"
#include "event_app.h"
#include "user_sleep.h"

void SystemSleepInit(void)
{
#if (defined(HAL_SLEEP)) && (HAL_SLEEP == TRUE)
  sys_safe_access_enable();
  R8_SLP_WAKE_CTRL |= RB_SLP_RTC_WAKE;
  sys_safe_access_disable();
  sys_safe_access_enable();
  R8_RTC_MODE_CTRL |= RB_RTC_TRIG_EN;
  sys_safe_access_disable();
  PFIC_EnableIRQ(RTC_IRQn);
#endif
}

uint32_t SystemIntoLowPower(uint32_t Time)
{
#if (defined(HAL_SLEEP)) && (HAL_SLEEP == TRUE)
  volatile uint32_t i;
  uint32_t time_tign, time_sleep, time_curr;
  uint32_t irq_status;

  if (Time <= WAKE_UP_RTC_MAX_TIME)
  {
    time_tign = Time + (RTC_MAX_COUNT - WAKE_UP_RTC_MAX_TIME);
  }
  else
  {
    time_tign = Time - WAKE_UP_RTC_MAX_TIME;
  }

  SYS_DisableAllIrq(&irq_status);
  time_curr = RTC_GetCycle32k();
  if (time_tign < time_curr)
  {
    time_sleep = time_tign + (RTC_MAX_COUNT - time_curr);
  }
  else
  {
    time_sleep = time_tign - time_curr;
  }

  if ((time_sleep < SLEEP_RTC_MIN_TIME) ||(time_sleep > SLEEP_RTC_MAX_TIME))
  {
    SYS_RecoverIrq(irq_status);
    return 2;
  }

  RtcSetTiggerTime(time_tign);
  SYS_RecoverIrq(irq_status);

#if (DEBUG == Debug_UART1)
  while ((R8_UART1_LSR & RB_LSR_TX_ALL_EMP) == 0)
  {
    __nop();
  }
#endif

  if ((!RtcGetIrqnTiggerEn()) && (EventGetDeviceWakeupFlagBit() != true))
  {
    LowPower_Sleep(RB_PWR_RAM32K | RB_PWR_RAM96K | RB_PWR_EXTEND);
    R8_RTC_FLAG_CTRL = (RB_RTC_TMR_CLR | RB_RTC_TRIG_CLR);
    RtcSetTiggerTime(Time);
    sys_safe_access_enable();
    R8_HFCK_PWR_CTRL |= RB_CLK_XT32M_KEEP;
    sys_safe_access_disable();

    if (!RtcGetIrqnTiggerEn())
    {
      LowPower_Idle();
    }

    R8_RTC_FLAG_CTRL = (RB_RTC_TMR_CLR | RB_RTC_TRIG_CLR);
    HSECFG_Current(HSE_RCur_100);

    return 0;
  }
#endif

  return 3;
}
